package cn.tedu.springdemo.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

//@Component
public class BeanPostProcessorDemo
    implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(
            Object bean, String beanName) throws BeansException {
        //此方法,在Bean对象创建以后, 执行初始化方法之前执行
        //每个JavaBean 创建以后, 都会执行一次
        if (beanName.equals("demoBean")) {
            System.out.println("执行:postProcessBeforeInitialization");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(
            Object bean, String beanName) throws BeansException {
        //此方法, 在Bean对象初始化以后执行
        //每个JavaBean初始化以后都会执行一次
        if (beanName.equals("demoBean")) {
            System.out.println("执行:postProcessAfterInitialization");
            Enhancer e = new Enhancer();
            MyInterceptor interceptor = new MyInterceptor();
            //bean 是Spring 创建的DemoBean对象
            interceptor.target = (DemoBean) bean;
            e.setSuperclass(DemoBean.class);
            e.setCallback(interceptor);
            DemoBean proxy = (DemoBean) e.create();
            return proxy;
        }
        return bean;
    }
}
class MyInterceptor implements MethodInterceptor{
    DemoBean target;
    @Override
    public Object intercept(
            Object o, Method method,
            Object[] args,
            MethodProxy methodProxy) throws Throwable {
        System.out.println("在方法之前执行");
        Object value = method.invoke(target, args);
        return value;
    }
}